import re, xlrd
from app.models import *

# 读取excel数据
def read_xls_cls(filename):
    data = xlrd.open_workbook(filename)
    sheets = data.sheets()
    data_list = []
    for sheet in sheets:
        lines = []
        name = sheet.name
        for r in range(sheet.nrows):
            col = []
            for c in range(sheet.ncols):
                col.append(sheet.cell(r, c).value)
            lines.append(col)
        data_list.append(lines)
    return data_list

def shop_cls():
    shop_list = []
    childs = read_xls_cls("data/product.xlsx")[0]
    child_sales_dict = {}
    data_dict = {}
    for line in childs[1:]:
        shop = line[7]
        evaluate = int(line[5])
        if shop not in child_sales_dict:
            child_sales_dict[shop] = 0
        if shop not in data_dict:
            data_dict[shop] = []
        child_sales_dict[shop] = child_sales_dict[shop] + evaluate
        data_dict[shop].append(line)

    f = open("data/shop.txt", "r", encoding="utf8")
    lines = f.readlines()
    f.close()

    for line in lines[1:]:
        line = line.strip()
        shop = line.split("\t")[0]
        suk = int(line.split("\t")[1])
        sales = int(line.split("\t")[2])
        d = {
            "name": shop,
            "suk": suk,
            "sales": sales,
            "child": []
        }
        childs = data_dict[shop]
        evaluate = child_sales_dict[shop]
        for child in childs:
            price = float(child[1])
            model = child[3]
            ev = int(child[5])
            if evaluate > 0:
                sale = int(sales*(ev/evaluate))
            else:
                sale = 0
            product = child[6]
            if re.search("\d\.\d匹", model):
                size = re.search("\d\.\d匹", model).group()
            else:
                try:
                    size = re.search("\d匹", model).group()
                except:
                    size = "1.5匹"
            d["child"].append({
                "price": price,
                "model": model,
                "size": size,
                "sales": sale,
                "product": product,
                "evaluate": ev
            })
        shop_list.append(d)

    for data in shop_list:
        st = ShopTab(
            name=data["name"],
            sku=data["suk"],
            sales=data["sales"]
        )
        st.save()
        child = data["child"]
        ll = []
        for c in child:
            pt = ProductTab(
                shop_id=st.id,
                price=c["price"],
                model=c["model"],
                size=c["size"],
                sales=c["sales"],
                product=c["product"],
                evaluate=c["evaluate"]
            )
            ll.append(pt)
        if ll:
            ProductTab.objects.bulk_create(ll)

